﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Net;
using System.Threading.Tasks;
using Stock.Core;
using Stock.Model;

public class ErrorHandlingMiddleware
{
	private readonly RequestDelegate next;
    private  readonly ILoggerService _l;

	public ErrorHandlingMiddleware(RequestDelegate next, ILoggerService l)
	{
		this.next = next;
        this._l = l;
	}

	public async Task Invoke(HttpContext context)
	{
		try
		{
			await next(context);
		}
		catch (Exception ex)
		{
			await HandleExceptionAsync(context, ex);
		}
	}

    private Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        //根据实际需求进行具体实现
        var subMsg = "";
        var msg = exception.Message;
        var code = HttpStatusCode.InternalServerError;
        if (exception is ArgumentException)
        {
            code = HttpStatusCode.BadRequest;
            subMsg = "业务处理错误";
        }
        else if (exception is UnauthorizedAccessException)
        {
            code = HttpStatusCode.Unauthorized;
            subMsg = "未授权";
        }
        if (code == HttpStatusCode.InternalServerError)
        {
            subMsg = "服务器错误";
        }
        var result = JsonConvert.SerializeObject(new BaseResult() { IsSuccess = false, Message = subMsg });
        //_l.Debug(new Stock.Core.Common.LogModel() { ActionName="123", Message="234" });

        _l.Error(new Stock.Core.Common.LogModel()
        {
            ExecuteStartTime = DateTime.Now,
            Message = msg,
            StackTrace = exception.StackTrace,
            ControllerName = context.Request.Path,
            HttpMethod = context.Request.Method
        });



        //var result = JsonConvert.SerializeObject(new { code = (int)code, sub_msg = subMsg, msg = msg });
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)code;
        return context.Response.WriteAsync(result);
    }
}

public static class ErrorHandlingExtensions
{
	public static IApplicationBuilder UseErrorHandling(this IApplicationBuilder builder)
	{
		return builder.UseMiddleware<ErrorHandlingMiddleware>();
	}
}
